<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\report;

use app\enum\ReportRecordEnum;
use app\model\PushReportRecordModel;
use app\model\ReportRecordModel;
use app\model\ReportRecordPushModel;
use app\model\StaffFsAccessTokenModel;
use app\model\StaffModel;
use app\service\alioss\AliossService;
use app\service\BaseService;
use app\service\imgick\ImagickService;
use app\service\notice\NoticeInterface;
use app\service\notice\NoticeService;
use app\service\report\kuaishou\KsProcessingDataService;
use app\service\report\ocean\OeProcessingDataService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;
use think\Model;

class ReportPullService extends BaseService
{
    /**
     * 获取待发送报表列表数据.
     *
     * @param int $sendTime 发送时间
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPullList(int $sendTime = 0, int $sendDate = 0)
    {
        return (new ReportRecordPushModel())
            ->where('hour', $sendTime)
            ->where('date', $sendDate)
            ->where('status', ReportRecordPushModel::STATUS_NO) // 0：待发送
            ->select();
    }

    /**
     * 获取历史报表列表数据 -- 昨天的需要更新的数据.
     *
     * @param int $sendDate 日期
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getHistoryList(int $sendDate = 0)
    {
        return (new ReportRecordPushModel())
            ->where('date', $sendDate)
            ->where('is_sync', ReportRecordPushModel::SYNC_NO) // 0：历史数据未同步
            ->select();
    }

    /**
     * 获取已同步数据报表.
     *
     * @return array|Collection|ReportRecordModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPullSyncList()
    {
        return (new ReportRecordPushModel())
            ->where('status', ReportRecordPushModel::STATUS_SYNC)
            ->select();
    }

    /**
     * 获取实时发送报表列表数据.
     * @return array|Collection|ReportRecordModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPullSendList(int $sendDate = 0)
    {
        return (new ReportRecordPushModel())
            ->where('status', ReportRecordPushModel::STATUS_WAIT_SEND) // 3：待发送
            ->where('date', $sendDate)
            ->select();
    }

    /**
     * 获取发送日报表数据.
     *
     * @param ReportRecordModel $obj 报表对象
     * @param int $sendDate 发送时间
     */
    public static function setFetchData(ReportRecordModel $obj, int $sendDate = 0): bool
    {
        if (! $obj->getKey()) {
            return self::setError('报表数据ID失败');
        }
        if ($obj->getAttr('is_send') == ReportRecordModel::SEND_NO) {
            return self::setError('报表数据已关闭');
        }
        $sendTime = json_decode($obj->getAttr('send_time'), true);
        if (! $sendTime) {
            return true;
        }
        try {
            Db::startTrans();
            foreach ($sendTime as $val) {
                $sendHour = intval($val);
                $model = ReportPullService::getPushReportRecordModel($obj->getKey(), $sendDate, $sendHour);
                if (! $model instanceof ReportRecordPushModel) {
                    throw new \Exception('获取发送时报记录模型失败');
                }
                $model->setAttrs([
                    'report_record_id' => $obj->getKey(),
                    'receive_staff_ids' => $obj->getAttr('receive_staff_ids'),
                    'date' => $sendDate,
                    'hour' => $sendHour,
                    'set_date' => time(),
                ]);
                $model->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
        return true;
    }

    /**
     * 获取当天需要发送的日报数据.
     *
     * @param int $reportRecordId 报表id
     * @param int $sendDate 发送日期
     * @param int $sendHour 发送时段
     * @return null|array|mixed|Model|ReportRecordPushModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPushReportRecordModel(int $reportRecordId = 0, int $sendDate = 0, int $sendHour = 0)
    {
        $where = [
            'report_record_id' => $reportRecordId,
            'date' => $sendDate,
            'hour' => $sendHour,
        ];
        $model = (new ReportRecordPushModel())->where($where)->field(true)->find();
        if (! $model instanceof ReportRecordPushModel) {
            $model = new ReportRecordPushModel();
        }
        return $model;
    }

    /**
     * 获取当天发送日报表数据.
     * @param int $date 发送日期
     * @param int $sendTime 发送时间
     * @return array|bool|Collection|PushReportRecordModel[]
     */
    public static function getPushReportRecord(int $date = 0, int $sendTime = 0)
    {
        try {
            return (new ReportRecordPushModel())
                ->where('date', $date)
                ->where('hour', '<=', $sendTime)
                ->select();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 设置发送日报表队列.
     * @param int $reportRecordId 报表id
     */
    public static function setPushReportRecordList(int $reportRecordId = 0): bool
    {
        $redis = Cache::store('redis')->handler();
        $key = ReportRecordEnum::CACHE_CONFIG['push_report_record_list'];
        $redis->rPush($key, $reportRecordId);
        return true;
    }

    /**
     * 获取需要发送的日报数据.
     * @param int $reportRecordId 报表主表id
     * @return bool|void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPushReportRecordSend(int $reportRecordId = 0)
    {
        $model = (new ReportRecordPushModel())->find($reportRecordId);
        if (! $model instanceof ReportRecordPushModel || ! $model->getKey()) {
            return self::setError('报表数据查收失败');
        }
        try {
            $item = (new ReportRecordModel())->where('is_send', ReportRecordModel::SEND_YES)->find($model['report_record_id']);
            if (! empty($item)) {
                if (empty($model->getAttr('file_url'))) {
                    $item = $item->toArray();
                    $item['sendDate'] = $model->getAttr('date');
                    $item['sendTime'] = $model->getAttr('hour');
                    // 处理数据
                    if ($item['media_id'] == ReportRecordEnum::OE_MEDIA) {
                        $data = OeProcessingDataService::processingData($item);
                    } elseif ($item['media_id'] == ReportRecordEnum::KS_MEDIA) {
                        $data = KsProcessingDataService::processingData($item);
                    }
                    $excelData = ! empty($data['data']) ? $data['data'] : [];
                    $totalData = ! empty($data['total']) ? $data['total'] : [];
                    // 生成excel文件
                    $fileUrl = self::getReportExcel($excelData, $item, $totalData);
                    unset($data, $excelData, $totalData);
                } else {
                    $fileUrl = $model->getAttr('file_url');
                }
                if ($fileUrl) {
                    $model->setAttr('file_url', $fileUrl);
                    $model->setAttr('status', ReportRecordPushModel::STATUS_WAIT_SEND);
                    if (! $model->save()) {
                        return self::setError('添加发送文件存储失败');
                    }
                    return true;
                }
            } else {
                $model->setAttr('status', ReportRecordPushModel::STATUS_FAIL);
                $model->setAttr('error_msg', '暂无数据');
                $model->save();
                return self::setError('暂无数据');
            }
        } catch (\Exception $e) {
            $model->setAttr('status', ReportRecordPushModel::STATUS_FAIL);
            $model->setAttr('error_msg', $e->getMessage());
            $model->save();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取需要发送的日报数据.
     * @param int $reportRecordId 发送id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getPushReportSend(int $reportRecordId = 0): bool
    {
        $model = (new ReportRecordPushModel())->where('status', ReportRecordPushModel::STATUS_WAIT_SEND)->find($reportRecordId);
        if (! $model instanceof ReportRecordPushModel || ! $model->getKey()) {
            return self::setError('发送报表数据查询失败');
        }
        try {
            $item = (new ReportRecordModel())->where('is_send', ReportRecordModel::SEND_YES)->find($model['report_record_id']);
            if (! $item instanceof ReportRecordModel || ! $item->getKey()) {
                $model->setAttr('status', ReportRecordPushModel::STATUS_FAIL);
                $model->setAttr('error_msg', '暂无数据');
                $model->save();
                return self::setError(date('Y-m-d H:i:s') . 'id为' . $reportRecordId . '暂无数据');
            }
            $fileUrl = $model->getAttr('file_url');
            if (! $fileUrl) {
                return self::setError(date('Y-m-d H:i:s') . 'id为' . $reportRecordId . '的报表生成excel失败');
            }
            // 发送类型
            $type = $item['push_mode'];
            // 推送消息接受人
            $receiveStaffIds = json_decode($item['receive_staff_ids'], true);
            if ($type == ReportRecordEnum::REPORT_RECORD_PUSH_MODE_MAILBOX) {
                // 邮箱
                $toEmails = (new StaffModel())->whereIn('id', $receiveStaffIds)->column('email');
                $service = NoticeService::getInstance($type);
                if (! $service instanceof NoticeInterface) {
                    return self::setError('实例化消息服务错误');
                }
                $sendDate = date('Y-m-d', strtotime(strval($model->getAttr('date'))));
                $subject = 'V2【' . ReportRecordEnum::REPORT_RECORD_DATE_TYPE[$item['report_date_type']] . '】' . $item['report_name'];
                $content_body = <<<EOF
                                            				                <html>
                                            				                <body>
                                            				                <p>报表日期：{$sendDate}</p>
                                            				                <p>报表时间：{$model->getAttr('hour')}:00</p>
                                            				                <p>客户自定义报表请见附件</p>
                                            				                </body>
                                            				                </html>
                            EOF;
                $send_result = $service->sendHtmlMail($toEmails, $subject, $content_body, [$model->getAttr('file_url')]);
                // 发送成功记录
                return self::updateStatus($send_result, $receiveStaffIds, $model);
            }
            if ($type == ReportRecordEnum::REPORT_RECORD_PUSH_MODE_NAIL) {
                // 钉钉
                $service = NoticeService::getInstance($type);
                if (! $service instanceof NoticeInterface) {
                    return self::setError('实例化消息服务错误');
                }
                $cardCode = sprintf(ReportRecordEnum::DING_CARD_TEMPLATE, ReportRecordEnum::REPORT_RECORD_DATE_TYPE[$item['report_date_type']], $item['report_name'], $model->getAttr('date'), $model->getAttr('hour'), $model->getAttr('file_url'));
                $successStaffIds = [];
                $rs = [];
                foreach ($receiveStaffIds as $staffId) {
                    $userId = $service->getUsersIdByPhone($staffId);
                    $res = $service->SendCardMessages(strval($userId), $cardCode);
                    if ($res) {
                        // 发送成功
                        $successStaffIds[] = $staffId;
                        $rs[] = $res;
                    }
                }
                // 发送成功记录
                return self::updateStatus($rs, $successStaffIds, $model);
            }
            if ($type == ReportRecordEnum::REPORT_RECORD_PUSH_MODE_FS) {
                // 飞书
                $service = NoticeService::getInstance($type);
                if (! $service instanceof NoticeInterface) {
                    return self::setError('实例化消息服务错误');
                }
                $openIds = [];
                $successStaffIds = [];
                foreach ($receiveStaffIds as $staffId) {
                    $staffModel = StaffModel::where('status', 1)->find($staffId);
                    if (! $staffModel instanceof StaffModel || ! $staffModel->getKey()) {
                        continue;
                    }
                    $openId = StaffFsAccessTokenModel::where('staff_id', $staffModel->getKey())->value('open_id');
                    if ($openId) {
                        $openIds[] = $openId;
                        $successStaffIds[] = $staffModel->getKey();
                    }
                }
                if (! empty($openIds)) {
                    $array = [
                        'msg_type' => 'interactive',
                        'open_ids' => $openIds,
                        'card' => [
                            'config' => [
                                'wide_screen_mode' => true,
                            ],
                            'header' => [
                                'template' => 'blue',
                                'title' => [
                                    'content' => 'V2【' . ReportRecordEnum::REPORT_RECORD_DATE_TYPE[$item['report_date_type']] . '】' . $item['report_name'],
                                    'tag' => 'plain_text',
                                ],
                            ],
                            'elements' => [
                                [
                                    'fields' => [
                                        [
                                            'is_short' => true,
                                            'text' => [
                                                'content' => "**📅 报表日期：**\n" . date('Y-m-d', strtotime(strval($model->getAttr('date')))),
                                                'tag' => 'lark_md',
                                            ],
                                        ],
                                        [
                                            'is_short' => true,
                                            'text' => [
                                                'content' => "**🕙 报表时间：**\n" . $model->getAttr('hour') . ':00',
                                                'tag' => 'lark_md',
                                            ],
                                        ],
                                    ],
                                    'tag' => 'div',
                                ],
                                [
                                    'actions' => [
                                        [
                                            'tag' => 'button',
                                            'text' => [
                                                'content' => '🔎 查看报表详情',
                                                'tag' => 'plain_text',
                                            ],
                                            'type' => 'primary',
                                            'url' => $model->getAttr('file_url'),
                                        ],
                                    ],
                                    'tag' => 'action',
                                ],
                            ],
                        ],
                    ];
                    $res = $service->sendBatchMessage($array);
                    // 发送成功记录
                    return self::updateStatus($res, $successStaffIds, $model);
                }
                return self::setError('未知飞书用户');
            }
            if ($type == ReportRecordEnum::REPORT_RECORD_PUSH_MODE_QYWX) {
                // 企业微信
                $service = NoticeService::getInstance($type);
                if (! $service instanceof NoticeInterface) {
                    return self::setError('实例化消息服务错误');
                }
                // 推送消息接受人
                $memberId = $service->getMember($receiveStaffIds);
                $data = [
                    'touser' => $memberId,
                    'msgtype' => 'textcard',
                    'agentid' => 1000004,
                    'textcard' => [
                        'title' => 'V2【' . ReportRecordEnum::REPORT_RECORD_DATE_TYPE[$item['report_date_type']] . '】' . $item['report_name'],
                        'description' => '📅报表日期：' . $model->getAttr('date') . "\n🕙报表时间：" . $model->getAttr('hour') . ':00',
                        'url' => $model->getAttr('file_url'),
                        'btntxt' => '🔎 详情',
                    ],
                ];
                $res = $service->sendMessages($data);
                // 发送成功记录
                return self::updateStatus($res, $receiveStaffIds, $model);
            }
            return true;
        } catch (\Exception $e) {
            $model->setAttr('status', ReportRecordPushModel::STATUS_WAIT_SEND);
            $model->setAttr('error_msg', $e->getMessage());
            $model->save();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取包周报内容添加到内容表.
     *
     * @param int $pullId 报表id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getReportRecordContent(int $pullId = 0): bool
    {
        $pullModel = (new ReportRecordPushModel())->find($pullId);
        if (! $pullModel instanceof ReportRecordPushModel || ! $pullModel->getKey()) {
            return self::setError('实时报表数据查询失败');
        }
        $obj = new ReportDataService($pullModel);
        return $obj->getData();
    }

    /**
     * 更新状态
     *
     * @param int $pullId 主键id
     * @param int $status 状态值
     */
    public static function setStatus(int $pullId = 0, int $status = 0): ReportRecordPushModel
    {
        return (new ReportRecordPushModel())->update(['status' => $status, 'update_time' => time()], ['id' => $pullId]);
    }

    /**
     * 生成excel.
     * @param mixed $contentData
     * @return bool|mixed|string
     */
    public static function getReportExcel(array $data, $contentData, array $totalData = [])
    {
        try {
            // 生成title
            $titles = [];
            $fields = json_decode($contentData['add_fields'], true);
            if ($contentData['report_date_type'] == 1) {
                // 时报
                array_unshift($fields, 'date', 'time');
            } else {
                // 日报
                array_unshift($fields, 'date');
            }
            if ($contentData['media_id'] == ReportRecordEnum::OE_MEDIA) {
                $fieldArr = ReportRecordEnum::REPORT_FIELDS_OE;
            } else {
                $fieldArr = ReportRecordEnum::REPORT_FIELDS_KS;
            }
            // 用户修改过字段名称则显示修改后的字段名称
            $contentData['add_fields_name'] = json_decode($contentData['add_fields_name'], true);
            if (! empty($contentData['add_fields_name'])) {
                foreach ($contentData['add_fields_name'] as $k => $v) {
                    if (! empty($fieldArr[$k])) {
                        $fieldArr[$k] = $v;
                    }
                }
            }
            // 自定义字段需要赋值名称 JSON_UNESCAPED_UNICODE
            if (! empty($contentData['custom_fields_name'])) {
                $contentData['custom_fields_name'] = json_decode($contentData['custom_fields_name'], true);
                foreach ($contentData['custom_fields_name'] as $v) {
                    $fieldArr[$v['field']] = $v['name'];
                }
            }
            foreach ($fields as $v) {
                $titles[] = $fieldArr[$v];
            }
            $obj = new Spreadsheet();

            // 横向单元格标识
            $cellName = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
                'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ',
                'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ'];
            // $obj->getActiveSheet(0)->setTitle('准患管理跟踪信息表');   //设置sheet名称
            $_row = 1;   // 设置纵向单元格标识
            if ($titles) {
                // $_cnt = count($title);
                // $obj->getActiveSheet(0)->mergeCells('A' . $_row . ':' . $cellName[$_cnt - 1] . $_row);   //合并单元格
                $i = 0;
                foreach ($titles as $title) {   // 设置列标题
                    $obj->setActiveSheetIndex(0)->getColumnDimension($cellName[$i])->setAutoSize(true);
                    $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i] . $_row, $title);

                    // 设置背景颜色
                    if (! empty($contentData['is_argb'])) {
                        $obj->getActiveSheet()->getStyle($cellName[$i] . $_row)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB($contentData['is_argb']);
                    }
                    ++$i;
                }
                ++$_row;
            }
            // 所有单元格居中显示
            $obj->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            // 填写数据
            if ($data) {
                // 判断是否合并同期时间单元格
                if ($contentData['is_merge'] == 0) {
                    $i = 0;
                    foreach ($data as $val) {
                        $j = 0;
                        foreach ($fields as $field) {
                            if (in_array($field, ['advertiser_id', 'campaign_id', 'ad_id', 'unit_id'])) {
                                $val[$field] .= ' ';
                            }
                            $val[$field] = ! empty($val[$field]) ? $val[$field] : 0;
                            $obj->getActiveSheet()->setCellValue($cellName[$j] . ($i + $_row), "{$val[$field]}");
                            ++$j;
                        }
                        ++$i;
                    }
                } else {
                    // 整理数据,分日期，+时间
                    $mergeData = [];
                    foreach ($data as $v) {
                        $mergeData[$v['time']][] = $v;
                    }
                    if ($titles[0] = 'date') {
                        // 查总数合并
                        $allCount = count($data);
                        $obj->getActiveSheet()->mergeCells('A' . $_row . ':A' . ($allCount + 1));   // 合并单元格
                    }

                    $i = 0;
                    foreach ($mergeData as $time => $v) {
                        $mergeCount = count($v);
                        foreach ($v as $val) {
                            $j = 0;
                            foreach ($fields as $field) {
                                if (in_array($field, ['advertiser_id', 'campaign_id', 'ad_id', 'unit_id'])) {
                                    $val[$field] .= ' ';
                                }
                                // 如果是时间，查询日期的总数并合并
                                if ($field == 'time') {
                                    if (! isset($nowTime) || $nowTime != $time) {
                                        // 合并单元格
                                        $obj->getActiveSheet()->mergeCells($cellName[$j] . ($i + $_row) . ':' . $cellName[$j] . ($i + $_row + $mergeCount - 1));   // 合并单元格
                                    }
                                }
                                $obj->getActiveSheet()->setCellValue($cellName[$j] . ($i + $_row), "{$val[$field]}");
                                ++$j;
                            }
                            $nowTime = $time;
                            ++$i;
                        }
                    }
                }

                // 判断是否有汇总
                if ($contentData['is_sum'] == 1 && ! empty($totalData)) {
                    $obj->getActiveSheet()->setCellValue('A' . ($i + $_row), '汇总');
                    $j = 0;
                    foreach ($fields as $field) {
                        if (isset($totalData[$field])) {
                            $obj->getActiveSheet()->setCellValue($cellName[$j] . ($i + $_row), "{$totalData[$field]}");
                        }
                        ++$j;
                    }
                }
            }
            $fileName = $contentData['report_name'] . date('YmdHis');
            if ($contentData['push_type'] == 1) {
                // excel
                $exts = '.xlsx';
                $objWrite = IOFactory::createWriter($obj, 'Xlsx');
                $savePath = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'downloads' . DIRECTORY_SEPARATOR;
                $objWrite->save($savePath . $fileName . $exts);
                $realPath = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'downloads' . DIRECTORY_SEPARATOR . $fileName . $exts;
            } else {
                // 创建TCPDF实例
                $pdf = new \TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
                $pdf->SetFont('stsongstdlight', '', '14');
                $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
                // 添加一页
                $pdf->AddPage();
                $data = $obj->getActiveSheet()->toArray();
                // 生成PDF内容
                $html = '<table border="1">';

                foreach ($data as $row) {
                    $html .= '<tr align="center">';

                    foreach ($row as $cell) {
                        $html .= '<td>' . htmlspecialchars(strval($cell ?? '')) . '</td>';
                    }
                    $html .= '</tr>';
                }

                $html .= '</table>';
                $pdf->setFooterData([0, 64, 0], [0, 64, 128]);
                // 设置页眉和页脚字体
                $pdf->setHeaderFont(['stsongstdlight', '', '10']);
                $pdf->setFooterFont(['helvetica', '', '8']);
                // 设置间距
                $pdf->SetMargins(15, 27, 15);
                $pdf->SetHeaderMargin(5);
                $pdf->SetFooterMargin(10);
                // 设置分页
                $pdf->SetAutoPageBreak(true, 25);
                // set image scale factor
                $pdf->setImageScale(1.25);
                // set default font subsetting mode
                $pdf->setFontSubsetting(true);
                // 设置默认等宽字体
                $pdf->SetDefaultMonospacedFont('courier');
                // 将HTML写入PDF
                $pdf->writeHTML($html, true, false, true, false, '');
                $exts = '.pdf';
                $realPath = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'downloads' . DIRECTORY_SEPARATOR . $fileName . $exts;
                $pdf->Output($realPath, 'F');
                $exts = '.jpg';
                $savePath = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'downloads' . DIRECTORY_SEPARATOR;
                $realPath = ImagickService::pdf2png($realPath, $savePath, $fileName);
            }
            if ($contentData['push_mode'] == 1) {
                // 邮箱
                return $realPath;
            }
            // sha1加密 生成文件名 连接后缀
            $fileName = 'report_file/' . date('Ymd') . '/' . $fileName . $exts;
            // 获取OSS参数值
            $res = (new AliossService())->uploadFile($realPath, $fileName);
            unlink($realPath);
            return $res;
        } catch (\Exception $e) {
            dump($e);
            return self::setError($e->getMessage());
        }
    }

    public static function updateStatus($res, $receiveStaffIds, $model): bool
    {
        if ($res) {
            // 发送成功，记录日志
            $model->setAttr('success_staff_id', json_encode($receiveStaffIds));
            $model->setAttr('status', ReportRecordPushModel::STATUS_SEND);
            $model->setAttr('error_msg', '发送成功');
        } else {
            // 修改发送失败的状态
            $model->setAttr('status', ReportRecordPushModel::STATUS_FAIL);
            $model->setAttr('error_msg', '发送失败');
        }
        if (! $model->save()) {
            return false;
        }
        return true;
    }
}
